import logging


logger = logging.getLogger(__name__)


class Space:
    def __init__(self, master, x, y, z):
        self.m = master
        self.sid = (x, y, z)
        self.data = self.m.spaces.get(self.sid, None)
        self.inv = [] #inventory


    def init_data(self, uid=None):
        if self.data is not None:
            logger.warning(f'space({self.sid}) already has data.')
        self.m.spaces[self.sid] = self.data = {'owner': uid}
        return self.data


    def look(self):
        if not self.data:
            return self.void_looking()

        s = self.m.Style
        owner = self.data.get('owner', None) if self.data else None
        x_owner = f'{s.HY}{owner}{s.N}'

        msg = f'{self.data}\n'
        msg = f'{self.data.get("short", "???")} {self.sid} [{x_owner}] - \n'
        msg += '\n'
        msg += f'{self.data.get("long", "???????")}\n'

        if self.inv:
            msg += f'There is here:\n'
            for ob in self.inv:
                if type(ob) == self.m.User:
                    msg += f'\t{ob.uid}\n'
                else:
                    msg += f'\t???\n'
        else:
            msg += 'There is nothing here.\n'

        return msg


    def void_looking(self):
        msg = f'Void ({self.sid}) - \n'
        msg += 'Here lies within an expanse of emptiness.\n'
        msg += 'There is nothing here.\n'
        return msg


    def move_in(self, ob):
        self.inv.append(ob)


    def move_out(self, ob):
        if ob in self.inv: self.inv.remove(ob)


    def find_ob(self, uid, index:int=1):
        if index <= 0: return None

        for ob in self.inv:
            if ob.uid == uid:
                if index == 1:
                    return ob
                else:
                    index -= 1

        return None


    def check_inv(self):
        for i in reversed(range(len(self.inv))):
            ob = self.inv[i] 
            if hasattr(ob, 'data') and 'location' in ob.data and ob.data['location'] == self.sid: continue
            self.inv.pop(i)


